package com.rinlink.gateway.jt808.jt808.webhook;

import com.rinlink.gateway.jt808.model.TerminalRequestMessage;
import com.rinlink.gateway.jt808.model.Jt808Header;
import com.rinlink.gateway.jt808.service.Jt808GatewayWebHookService;
import io.github.hylexus.jt808.dispatcher.RequestMsgDispatcher;
import io.github.hylexus.jt808.msg.RequestMsgMetadata;
import io.github.hylexus.jt808.msg.RequestMsgWrapper;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.BeanUtils;

public class Jt808WebHookDispatch implements RequestMsgDispatcher {

    private Jt808GatewayWebHookService jt808GatewayWebHookService;

    public Jt808WebHookDispatch(Jt808GatewayWebHookService jt808GatewayWebHookService) {
        this.jt808GatewayWebHookService = jt808GatewayWebHookService;
    }

    @Override
    public void doDispatch(RequestMsgWrapper wrapper) throws Exception {

        RequestMsgMetadata msg = wrapper.getMetadata();

        Jt808Header header = new Jt808Header();

        BeanUtils.copyProperties(msg.getHeader(),header);

        String body = Base64.encodeBase64String(msg.getBodyBytes());
        TerminalRequestMessage base64Jt808Message = new TerminalRequestMessage()
                .setHeader(header)
                .setBody(body);

        jt808GatewayWebHookService.terminalRequest(base64Jt808Message);
    }

}
